/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
//http://forums.sun.com/thread.jspa?threadID=772953
package relaibluetooth;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.bluetooth.*;
import javax.microedition.io.*;

import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;



/**
 *
 * @author Etienne
 */
public class relai implements Runnable{

private String m_strUrl;
UUID RFCOMM_UUID ;
private LocalDevice m_LclDevice = null;
private StreamConnectionNotifier  m_StrmNotf=null;
private StreamConnection m_StrmConn = null;
private boolean running=false;
private int mdp;
private ArrayList<Thread> threadList=null;
private Socket socketTcp;
private InetAddress addr;
private String stringAdress="GEITP111-08";
private int port;
private GuiRelai gui;
private int nbRep;

public relai()  {
  
    RFCOMM_UUID = new UUID(0x0003);
        initialize();
   
    }


    public void initialize(){
        gui=new GuiRelai();
         //on recupere le port sur lequel on va travailler
        port=gui.getPort();
        //on créé l url nécessaire à la connection bluetooth
      m_strUrl= "btspp://localhost:" + RFCOMM_UUID + ";name=rfcommtest;authorize=true";
        try {
            //on se connecte au serveur principal et on recupere le mdp
            addr = InetAddress.getByName(stringAdress);
           socketTcp = new Socket(addr, port);
        //on demarre le thread qui recevra le mot de passe
          
           mdp=getMdp();
        //   on démarre le thread qui attend les nouvelles questions
           System.out.println("test1");
            running=true;
           new Thread(this).start();
System.out.println("test2");
        } catch (UnknownHostException ex) {
            Logger.getLogger(relai.class.getName()).log(Level.SEVERE, null, ex);
        }
             catch (IOException ex) {
                Logger.getLogger(relai.class.getName()).log(Level.SEVERE, null, ex);
            }
System.out.println("test");
        try
        {

            running=true;
          //on créé le serveur bluetooth
              m_LclDevice = LocalDevice.getLocalDevice();

              m_LclDevice.setDiscoverable(DiscoveryAgent.GIAC);

              m_StrmNotf = (StreamConnectionNotifier)Connector.open(m_strUrl);
            
              while(running)
              {System.out.println("attente connection\n");
               
                    m_StrmConn = m_StrmNotf.acceptAndOpen();
                    System.out.println("connection opened \n");
                    //on créé un thread par connection
                    threadList.add(new Thread(new threadConnection(m_StrmConn,this)));
                    threadList.get(threadList.size()).run();
               }
             


        }
        catch (BluetoothStateException e)
        {
            System.err.println( "BluetoothStateException: " + e.getMessage() );
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        catch(Exception e)
        {
            System.err.println( "Exception: " + e.getMessage() );
        }
System.out.println("test3");
    }

public boolean getRunning()
{
    return running;
}

    public void relayVote(int vote) throws IOException{
        //on envoie le vote
    socketTcp.getOutputStream().write(vote);
    }

    public void relayDeblock(){
        //on reveille tous les thread en attente
         if(!(threadList==null))
         {if(!threadList.isEmpty() )
        this.notifyAll();
         }
        
     }

    public boolean acceptConnection(int mdp){
        if(this.mdp==mdp)
            {
                return true;
            }
        else return false;
    }


    public int getMdp(){
    int mdp=0;
        try {
            //20 : demande de mdp
            socketTcp.getOutputStream().write(20);

            mdp=socketTcp.getInputStream().read();
            System.out.println("mdp : "+ mdp);
        } catch (IOException ex) {
            Logger.getLogger(relai.class.getName()).log(Level.SEVERE, null, ex);
        }
    return mdp;}

    public int getNbRep()
    {return nbRep;}

    public void run() {
        int message=0;
      
      
        while (running==true)
        {
            try {
                message = socketTcp.getInputStream().read();
                System.out.println("deblocage : " + message);
                if(message!=40)
                {    relayDeblock();
                nbRep=message;}
                else {running=false;
                System.out.println("fin !");}
            } catch (IOException ex) {
                Logger.getLogger(relai.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}
